package com.atom.module.mvvm.base.viewmodel

import android.os.Bundle
import android.os.Looper
import com.atom.module.mvvm.base.ApiModel
import com.atom.module.mvvm.livedata.SingleLiveData

abstract class AbstractBaseViewModel<M : ApiModel> : AbstractViewModel<M> {

    constructor(model: M) : super(model)

    internal val startActivityAction = SingleLiveData<Map<String, Any>>()

    internal val toastAction = SingleLiveData<String>()

    internal val startActivityForResultAction = SingleLiveData<Map<String, Any>>()

    internal val finishAction = SingleLiveData<Unit>()

    internal val onBackPressedAction = SingleLiveData<Unit>()

    fun startActivity(clz: Class<*>, bundle: Bundle? = null) {
        val params: MutableMap<String, Any> = HashMap()
        params[ParameterField.CLASS] = clz
        if (bundle != null) {
            params[ParameterField.BUNDLE] = bundle
        }
        startActivityAction.postValue(params)
    }

    fun startActivityForResult(clz: Class<*>, resultCode: Int, bundle: Bundle? = null) {
        val params: MutableMap<String, Any> = HashMap()
        params[ParameterField.CLASS] = clz
        params[ParameterField.RESULT] = resultCode
        if (bundle != null) {
            params[ParameterField.BUNDLE] = bundle
        }
        startActivityForResultAction.postValue(params)
    }

    fun finish() {
        finishAction.postValue(Unit)
    }

    fun toast(toast: String) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            toastAction.setValue(toast)
        } else {
            toastAction.postValue(toast)
        }
    }

    fun onBackPressed() {
        onBackPressedAction.postValue(Unit)
    }

    object ParameterField {
        const val CLASS = "CLASS"
        const val BUNDLE = "BUNDLE"
        const val RESULT = "RESULT"
        const val REQUEST = "REQUEST"
    }
}
